import React, { FC, useMemo, useRef, useState } from 'react';
import './index.less';
import { Transfer, TransferProps } from 'antd';
import { useRequest } from '@@/plugin-request';
import * as API from '@/services';
import { useBackendEnum } from 'kf-web-library';
import { DndProvider, useDrop, useDrag } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import styled from 'styled-components';
import type { TransferKey } from 'antd/es/transfer/interface';
import { MenuOutlined } from '@ant-design/icons';

interface SearchItemManageProps {}

interface RecordType {
  key: string;
  title: string;
}

const ItemWrapper = styled.div`
  display: flex;
  justify-content: space-between;

  > .label {
    display: inline-block;
    max-width: calc(100% - 20px);
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  &.drop-over-downward {
    border-bottom: 2px dashed #1890ff;
  }

  &.drop-over-upward {
    border-top: 2px dashed #1890ff;
  }
`;

/**
 * 检索项管理 页面
 */
const SearchItemManage: FC<SearchItemManageProps> = (props) => {
  const { getBackendEnums } = useBackendEnum();

  const dataSource = useMemo<RecordType[]>(() => {
    return getBackendEnums('ConditionParaType')
      .filter((t) => !['SC'].includes(t.enumName))
      .map((t) => {
        return {
          key: t.enumName,
          title: t.enumDesc,
        };
      });
  }, []);

  const [targetKeys, setTargetKeys] = useState<TransferKey[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<TransferKey[]>([]);

  const siteAboutInfoReq = useRequest(() => API.querySiteAboutInfo(), {
    onSuccess: (res) => {
      setTargetKeys(res.articleSearchItems || []);
    },
  });

  const patchSiteAboutInfoReq = useRequest((p) => API.patchSiteAboutInfo(p), {
    manual: true,
  });

  const onChange = (nextTargetKeys) => {
    const articleSearchItems = (nextTargetKeys || []).filter((t) => dataSource.findIndex((d) => d.key === t) !== -1);
    patchSiteAboutInfoReq.run({ articleSearchItems }).then(() => {
      siteAboutInfoReq.run();
    });
  };

  const onSelectChange: TransferProps['onSelectChange'] = (sourceSelectedKeys, targetSelectedKeys) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  // change order
  const moveRow = async (dragIndex, hoverIndex) => {
    const clonedList = targetKeys;
    const el = clonedList.splice(dragIndex, 1)[0];
    clonedList.splice(hoverIndex, 0, el);
    onChange(clonedList);
  };

  return (
    <div className={'search-item-manage-container'}>
      <DndProvider backend={HTML5Backend}>
        <Transfer
          dataSource={dataSource}
          titles={['可用检索项', '展示检索项']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={onChange}
          onSelectChange={onSelectChange}
          //onScroll={handleScroll}
          render={(item) => {
            return (
              <DraggableItem
                index={targetKeys!.findIndex((key) => key === item.key)}
                label={item.title}
                moveRow={moveRow}
              />
            )
          }}
          disabled={false}
          oneWay
          style={{ marginBottom: 16 }}
        />
      </DndProvider>
    </div>
  );
};

const type = 'DraggableItem';
const DraggableItem = ({ index, label, moveRow }) => {
  const ref = useRef<any>();
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor) => {
      const { index: dragIndex } = monitor.getItem() || {} as any;
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ` drop-over-downward` : ` drop-over-upward`,
      };
    },
    drop: (item: any) => {
      moveRow(item.index, index);
    },
  });

  const [{ isDragging }, drag, preview] = useDrag({
    type,
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  preview(drop(ref));

  return (
    <ItemWrapper key={label} ref={ref} className={`${isOver ? dropClassName : ''}`}>
      <span className="label">
         {index !== -1 && (
           <span ref={drag} style={{cursor: 'move', marginRight: '12px'}}>
          <MenuOutlined />
        </span>
         )}
        {label}
      </span>

    </ItemWrapper>
  );
};

export default SearchItemManage;
